/*
 * File:   MainWindow.cpp
 * Author: Morpheus
 *
 * Created on 20 juin 2013, 13:19
 */


#include "MainWindow.h"
#include "QDirModelVeryLite.h"
#include "MergeMdiChild.h"
#include "FileLite.h"
#include "MyBatchMergeModel.h"
#include "ThreadBatchMerge.h"
#include "BatchMergeAboutDlg.h"
#include "SettingDlg.h"
#include "QFileInfeSorterFactory.h"
#include "ChoiseFolderDialog.h"
#include "BatchFilterDlg.h"
#include "MajBatch.h"


#include <QtWidgets/qfiledialog.h>
#include <QtCore/qdebug.h>
#include <QtWidgets/qmdisubwindow.h>
#include <QtCore/qiodevice.h>
#include <QtWidgets/qprogressdialog.h>
#include <QtWidgets/qwhatsthis.h>
#include <QtGui/QCloseEvent>
#include <QtPrintSupport/qprinter.h>
#include <QtCore/qsettings.h>


MainWindow::MainWindow() {
    widget.setupUi(this);
    {
        QAction* actionW = QWhatsThis::createAction(this);
        actionW->setIcon( QIcon(":/res/whatsthis.png") );
        widget.toolBar->addAction(actionW);
        widget.menuAide->addAction(actionW);
    }
    widget.customFilterBatch->setDefaultAction(widget.actionAddFilter);
    widget.customFilterBatch->addAction(widget.actionEditFilter);
    widget.customFilterBatch->addAction(widget.actionDelFilter);
    widget.customFilterBatch->setVisible(false);
    
    QDirModelVeryLite* sourceModel = new QDirModelVeryLite(this);
/*
    MySortFilterProxyModel* model = new MySortFilterProxyModel(this);
    model->setFilterKeyColumn(0);
    model->setFilterCaseSensitivity(Qt::CaseInsensitive);
    model->setFilterRole(Qt::DisplayRole);
    model->setFilterCaseSensitivity(Qt::CaseInsensitive);
    model->setDynamicSortFilter(true);
    
    model->setSourceModel(sourceModel);
    widget.treeView->setModel(model);
*/
    widget.treeView->setModel(sourceModel);
    widget.treeView->hideColumn(2);
    widget.treeView->hideColumn(4);
    
    widget.treeView->addAction(widget.actionCheckAll);
    widget.treeView->addAction(widget.actionCheckSelected);
    widget.treeView->addAction(widget.actionUnCheckAll);
    widget.treeView->addAction(widget.actionUnCheckSelected);
    
    MyBatchMergeModel* modelBatch = new MyBatchMergeModel(this);
    widget.listView->setModel(modelBatch);
    
    connect(widget.mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(updateSubWindow()));
    connect(widget.actionMosaique, SIGNAL(triggered()), widget.mdiArea, SLOT(tileSubWindows()));
    connect(widget.actionCascade, SIGNAL(triggered()), widget.mdiArea, SLOT(cascadeSubWindows()));
    connect(widget.actionCloseAll, SIGNAL(triggered()), widget.mdiArea, SLOT(closeAllSubWindows()));
}

void MainWindow::initialed() {
    MajBatch maj(this);
    connect(&maj, SIGNAL(showMessage(QString)), this, SIGNAL(showMessage(QString)));
    maj.checkUpdate();
    
    readSetting();
    
    reloadFilterBatch();
            
//    loadBatchesFromFile();
}


MainWindow::~MainWindow() {
}

void MainWindow::closeEvent(QCloseEvent* event){
    widget.mdiArea->closeAllSubWindows();
    if(widget.mdiArea->activeSubWindow() != NULL){
        event->ignore();
    }else{
        writeSetting();
        event->accept();
    }
}

void MainWindow::on_actionAddFolder_triggered(){
    ChoiseFolderDialog dlg(this);
    dlg.setFolderPath(m_lastDir);
    dlg.setNativeFolder(m_batchSetting.getBrowseFolderNative());
    if(dlg.exec() != QDialog::Accepted)
        return;

    QString filterName = dlg.getFilterName();
    QString folder = dlg.getFolderPath();
    if(folder.isEmpty())
        return;
    m_lastDir = folder;
//    QSortFilterProxyModel* model = qobject_cast<QSortFilterProxyModel*>(widget.treeView->model());
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());
    QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
    sourceModel->addFolder(folder, true, filterName);
    while(sourceModel->cdDown()){
        ;
    }
    sourceModel->cdUp();
    widget.treeView->expandAll();
    QApplication::restoreOverrideCursor();
}
/*
void MainWindow::OnFilterChanged(QString s){
    MySortFilterProxyModel* model = qobject_cast<MySortFilterProxyModel*>(widget.treeView->model());
    qDebug() << Q_FUNC_INFO;
    model->setFileName(widget.lineEditFilterName->text());
    model->setExtension(widget.lineEditFilterExt->text());
    model->updatedFilter();
}
*/
void MainWindow::on_actionRemoveFile_triggered(){
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());
    FileLite* root = sourceModel->getRoot();
    if(root == NULL)
        return;

    QStringList filesPath;
    foreach( FileLite* c, root->findChildren<FileLite*>()){
        if(c->isFile() && c->getCheckedState() == Qt::Checked){
            filesPath << c->getAbsoluteFilePath();
        }
    }
    if(filesPath.isEmpty())
        return;

    sourceModel->removeFiles(filesPath);
}

void MainWindow::on_actionEditConfig_triggered(){
/*
    QPrinter printer;
    {
        QPageSetupDialog dlg(&printer, this);
        dlg.exec();
    }
    {
        QPrintDialog dlg(&printer, this);
        dlg.setOption(QPrintDialog::PrintToFile, true);
        dlg.setOption(QPrintDialog::PrintSelection, false);
        dlg.setOption(QPrintDialog::PrintPageRange, false);
        dlg.setOption(QPrintDialog::PrintShowPageSize, true);
        dlg.setOption(QPrintDialog::PrintCollateCopies, false);
        dlg.exec();
    }
*/
    SettingDlg dlg(this);
    dlg.setBatchSetting(m_batchSetting);
    if(dlg.exec() == QDialog::Accepted){
        m_batchSetting = dlg.getBatchSetting();
    }
}
void MainWindow::on_actionAddFiles_triggered(){
    QStringList files = QFileDialog::getOpenFileNames(this, trUtf8("Sélectionnez des Fichiers"), m_lastDir);
    if(files.isEmpty())
        return;
    QFileInfo info(files[0]);
    m_lastDir = info.absolutePath();
//    QSortFilterProxyModel* model = qobject_cast<QSortFilterProxyModel*>(widget.treeView->model());
//    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(model->sourceModel());
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());
    QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
    sourceModel->addFiles(files);
    while(sourceModel->cdDown()){
        ;
    }
    sourceModel->cdUp();
    widget.treeView->expandAll();
    QApplication::restoreOverrideCursor();
}
void MainWindow::on_actionExecutSelectedBatch_triggered(){
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    QModelIndexList indexes = widget.listView->selectionModel()->selectedIndexes();
    if(indexes.isEmpty())
        return;
    QList<MyBatchMerge> list;
    foreach(QModelIndex index, indexes){
        MyBatchMerge batch = model->getBatch(index);
        batch = DAOBatchMerge::self()->getBatchMerge(batch.getUUID());
        list << batch;
    }
    QByteArray array;
    QDataStream in(&array, QIODevice::WriteOnly);
    in << list;
    launchThread(array);
}
void MainWindow::on_actionExecutAllBatch_triggered(){
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    if(model->rowCount() == 0)
        return;
    QList<MyBatchMerge> listTmp = model->getAllBatch();
    QList<MyBatchMerge> list;
    while(listTmp.size()){
        list << DAOBatchMerge::self()->getBatchMerge(listTmp.takeFirst().getUUID());
    }
    
    QByteArray array;
    QDataStream in(&array, QIODevice::WriteOnly);
    in << list;
    launchThread(array);
}
void MainWindow::on_actionCreateBatch_triggered(){
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());
    FileLite* root = sourceModel->getRoot();
    if(root == NULL)
        return;

    QList<MyFileInfo>filesPath;
    int sortCode = m_batchSetting.getSorterFileId();
    QString sortParam = m_batchSetting.getSorterFileParam();
    foreach( FileLite* c, root->findChildren<FileLite*>()){
        if(c->isFile() && c->getCheckedState() == Qt::Checked){
            filesPath << MyFileInfo(QFileInfo(c->getAbsoluteFilePath()), sortCode, sortParam);
        }
    }
    if(filesPath.isEmpty()){
        return;
    }

    qSort(filesPath);

    QDir rootDir(qApp->applicationDirPath());
    
    MyBatchMerge batch;
    batch.setName(filesPath.first().d->info.baseName());
    batch.setSaveFilePatern(m_batchSetting.getDefaultSavePatern());
    batch.setSaveFileFormat(m_batchSetting.getDefaultSaveFormat());

    for(int i = 0; i < filesPath.size(); i++){
        QFileInfo infoFile = filesPath.at(i).d->info;
        if(m_batchSetting.getCreateScriptBefore()){
            MyBatchUnit unitElem;
            QString patern = m_batchSetting.getScriptBeforePatern();
            if(patern.contains("%1")){
                patern = patern.arg((i+1)*2);
            }
            unitElem.setContentText(patern);
            batch.insertBatch(unitElem);
        }

        MyBatchUnit unitElem;
        unitElem.setFilePath(rootDir.relativeFilePath(infoFile.absoluteFilePath()));
        batch.insertBatch(unitElem);
    }
    
    DAOBatchMerge::self()->saveBatchMerge(batch);
    
    MergeMdiChild* child = createMdiChild();
    child->setBatchMerge(batch);
    if(m_batchSetting.getMdiShowMode() == 0){
        child->show();
    }else{
        child->showMaximized();
    }
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    model->setCurBatchMerge(batch.getUUID());
    
    on_comboFilterBatch_currentIndexChanged(widget.comboFilterBatch->currentIndex());
}
void MainWindow::on_actionDeleteBatch_triggered(){
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    QModelIndexList indexes = widget.listView->selectionModel()->selectedIndexes();
    QList<int> list;
    foreach(QModelIndex index, indexes){
        int uid = model->getBatch(index).getUUID();
        list << uid;
        QMdiSubWindow* w = findMdiChild(uid);
        if(w){
            MergeMdiChild* child = qobject_cast<MergeMdiChild*>(w->widget());
            child->on_pushButtonCancel_clicked();
        }
    }
    DAOBatchMerge::self()->removeBatchMerge(list);
    model->removeBatch(list);
}
void MainWindow::on_listView_activated(const QModelIndex &index){
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    MyBatchMerge batch = model->getBatch(index);
    
    batch = DAOBatchMerge::self()->getBatchMerge(batch.getUUID());
    
    model->setCurBatchMerge(batch.getUUID());
    
    QMdiSubWindow* w = findMdiChild(batch.getUUID());
    setActiveSubWindow(w);
    if(w == NULL){
        MergeMdiChild *child = createMdiChild();
        child->setBatchMerge(batch);
        if(m_batchSetting.getMdiShowMode() == 0){
            child->show();
        }else{
            child->showMaximized();
        }
    }
}
void MainWindow::OnThreadFinishWthSuccessOneBatch(const int& uuid){
    DAOBatchMerge::self()->updateBatchMergeDoWthSucces(uuid, true);
    
    on_comboFilterBatch_currentIndexChanged(widget.comboFilterBatch->currentIndex());
}

void MainWindow::OnBatchUpdated(const QByteArray& array){
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    QDataStream out(array);
    MyBatchMerge batch;
    out >> batch;
    if(out.status() == QDataStream::ReadCorruptData)
        return;
    
    DAOBatchMerge::self()->saveBatchMerge(batch);
    model->appendBatch(batch);
}

MergeMdiChild* MainWindow::createMdiChild(){
    MergeMdiChild *child = new MergeMdiChild;
    widget.mdiArea->addSubWindow(child);

    connect(child, SIGNAL(savedBatch(QByteArray)), this, SLOT(OnBatchUpdated(QByteArray)));

    return child;
}
MergeMdiChild* MainWindow::activeMdiChild(){
    if (QMdiSubWindow *activeSubWindow = widget.mdiArea->activeSubWindow())
        return qobject_cast<MergeMdiChild *>(activeSubWindow->widget());
    return 0;
}
QMdiSubWindow* MainWindow::findMdiChild(const int &uuid){
    foreach (QMdiSubWindow *window, widget.mdiArea->subWindowList()) {
        MergeMdiChild *mdiChild = qobject_cast<MergeMdiChild *>(window->widget());
        if (mdiChild->getUuid() == uuid)
            return window;
    }
    return 0;
}
void MainWindow::setActiveSubWindow(QWidget *window){
    if (!window)
        return;
    widget.mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow *>(window));
}
void MainWindow::updateSubWindow(){
    MergeMdiChild *child = activeMdiChild();
    MyBatchMergeModel* modelBatch = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    if(child){
        modelBatch->setCurBatchMerge(child->getUuid());
        widget.listView->scrollTo(modelBatch->getBatchIndex(child->getUuid()));
    }else{
        modelBatch->setCurBatchMerge(-1);
    }
}
void MainWindow::launchThread(const QByteArray& array){
    QProgressDialog* progress = new QProgressDialog(this);
    progress->setWindowModality(Qt::WindowModal);
    progress->setAutoClose(false);
    ThreadBatchMerge* thread = new ThreadBatchMerge(array, m_batchSetting.getSettingPrint(), this);
    connect(thread, SIGNAL(information(QString)), progress, SLOT(setCancelButtonText(QString)));
    connect(thread, SIGNAL(description(QString)), progress, SLOT(setLabelText(QString)));
    connect(thread, SIGNAL(range(int, int)), progress, SLOT(setRange(int, int)));
    connect(thread, SIGNAL(progress(int)), progress, SLOT(setValue(int)));
    connect(thread, SIGNAL(started()), progress, SLOT(show()));
    connect(thread, SIGNAL(batchUuidDoSuccess(int)), this, SLOT(OnThreadFinishWthSuccessOneBatch(int)));

    connect(progress, SIGNAL(finished(int)), thread, SLOT(quit()));
    thread->start(); 
}
void MainWindow::on_actionAbout_triggered(){
    BatchMergeAboutDlg dlg(this);
    dlg.setModal(true);
    dlg.exec();
}
void MainWindow::on_actionAboutQt_triggered(){
    qApp->aboutQt();
}
void MainWindow::on_actionAddFilter_triggered(){
//    BatchMergeCriteria criteria = DAOBatchMerge::self()->getCurrentBatchCriteria();
    BatchFilterDlg dlg(this);
    dlg.setModal(true);
//    dlg.setCritetia(criteria);
    if(dlg.exec() == QDialog::Accepted){
//        criteria = dlg.getCritetia();
//        QByteArray array;
//        QDataStream in(&array, QIODevice::WriteOnly);
//        in << criteria;
//        setUpdatesEnabled(false);
//        if(widget.comboFilterBatch->count() == 6){
//            widget.comboFilterBatch->addItem(tr("Personnalisé"));
//        }
//        widget.comboFilterBatch->setItemData(6, array);
//        widget.comboFilterBatch->setCurrentIndex(6);
//        setUpdatesEnabled(true);
//        on_comboFilterBatch_currentIndexChanged(6);
    }
}
void MainWindow::on_comboFilterBatch_currentIndexChanged(const int& idx){
    if(!updatesEnabled())
        return;
    int id = widget.comboFilterBatch->itemData(idx).toInt();
    BatchMergeCriteria criteria = DAOBatchMerge::self()->getBatchCriteria(id);
    QVariantList alreadyOpenedBatchMerge;
    foreach (QMdiSubWindow *window, widget.mdiArea->subWindowList()) {
        MergeMdiChild *mdiChild = qobject_cast<MergeMdiChild *>(window->widget());
        alreadyOpenedBatchMerge << mdiChild->getUuid();
    }
    
    QList<MyBatchMerge> list = DAOBatchMerge::self()->getBatchMergeByCriteria(criteria, alreadyOpenedBatchMerge);
    MyBatchMergeModel* model = qobject_cast<MyBatchMergeModel*>(widget.listView->model());
    model->setBatchs(list);
}

void MainWindow::readSetting(){
    QDir dir(qApp->applicationDirPath());
    QSettings setting(dir.absoluteFilePath("./FileMergerData/FileMerger.ini"), QSettings::IniFormat, this);

    setting.beginGroup(tr("General"));
    m_lastDir = setting.value(tr("LastDir"), qApp->applicationDirPath()).toString();
    if(setting.contains(tr("Geometrie"))){
        restoreGeometry(setting.value(tr("Geometrie")).toByteArray());
    }
    if(setting.contains(tr("State"))){
        restoreState(setting.value(tr("State")).toByteArray());
    }
    if(setting.contains(tr("Explorer.Geometrie"))){
        widget.treeView->restoreGeometry(setting.value(tr("Explorer.Geometrie")).toByteArray());
    }
    if(setting.contains(tr("Explorer.Header.Geometrie"))){
        widget.treeView->header()->restoreGeometry(setting.value(tr("Explorer.Header.Geometrie")).toByteArray());
    }
    if(setting.contains(tr("Explorer.Header.State"))){
        widget.treeView->header()->restoreState(setting.value(tr("Explorer.Header.State")).toByteArray());
    }
    if(setting.contains(tr("Batchs.Geometrie"))){
        widget.listView->restoreGeometry(setting.value(tr("Batchs.Geometrie")).toByteArray());
    }
    if(setting.contains("BrowseFolderNative")){
        m_batchSetting.setBrowseFolderNative(setting.value(tr("BrowseFolderNative")).toBool());
    }
    if(setting.contains("MdiShowMode")){
        m_batchSetting.setMdiShowMode(setting.value(tr("MdiShowMode")).toInt());
    }

    setting.endGroup();
    setting.beginGroup(tr("BatchCreationOption"));

    if(setting.contains("CreateScriptBefore")){
        m_batchSetting.setCreateScriptBefore(setting.value(tr("CreateScriptBefore")).toBool());
    }
    if(setting.contains("DefaultSaveFormat")){
        m_batchSetting.setDefaultSaveFormat(setting.value(tr("DefaultSaveFormat")).toString());
    }
    if(setting.contains("DefaultSavePatern")){
        m_batchSetting.setDefaultSavePatern(setting.value(tr("DefaultSavePatern")).toString());
    }
    if(setting.contains("ScriptBeforePatern")){
        m_batchSetting.setScriptBeforePatern(setting.value(tr("ScriptBeforePatern")).toString());
    }
    if(setting.contains("SorterFileId")){
        m_batchSetting.setSorterFileId(setting.value(tr("SorterFileId")).toInt());
    }
    if(setting.contains("SorterFileParam")){
        m_batchSetting.setSorterFileParam(setting.value(tr("SorterFileParam")).toString());
    }

    setting.endGroup();
    setting.beginGroup(tr("PrintOption"));

    if(setting.contains("Orientation")){
        m_batchSetting.setOrientation(setting.value(tr("Orientation")).toInt());
    }
    if(setting.contains("PaperSize")){
        m_batchSetting.setPaperSize(setting.value(tr("PaperSize")).toInt());
    }
    if(setting.contains("Resolution")){
        m_batchSetting.setResolution(setting.value(tr("Resolution")).toInt());
    }
    if(setting.contains("Color")){
        m_batchSetting.setColor(setting.value(tr("Color")).toInt());
    }
    if(setting.contains("MargingBottom")){
        m_batchSetting.setMargingBottom(setting.value(tr("MargingBottom")).toInt());
    }
    if(setting.contains("MargingLeft")){
        m_batchSetting.setMargingLeft(setting.value(tr("MargingLeft")).toInt());
    }
    if(setting.contains("MargingRight")){
        m_batchSetting.setMargingRight(setting.value(tr("MargingRight")).toInt());
    }
    if(setting.contains("MargingTop")){
        m_batchSetting.setMargingTop(setting.value(tr("MargingTop")).toInt());
    }

    setting.endGroup();
}
void MainWindow::writeSetting(){
    QDir dir(qApp->applicationDirPath());
    QSettings setting(dir.absoluteFilePath("./FileMergerData/FileMerger.ini"), QSettings::IniFormat, this);
    setting.beginGroup(tr("General"));
    setting.setValue(tr("Version"), qApp->applicationVersion());
    setting.setValue(tr("LastDir"), m_lastDir);
    setting.setValue(tr("Geometrie"), saveGeometry());
    setting.setValue(tr("State"), saveState());
    setting.setValue(tr("Explorer.Geometrie"), widget.treeView->saveGeometry());
    setting.setValue(tr("Explorer.Header.Geometrie"), widget.treeView->header()->saveGeometry());
    setting.setValue(tr("Explorer.Header.State"), widget.treeView->header()->saveState());
//    setting.setValue(tr("Batchs.Geometrie"), widget.listView->saveGeometry());

    setting.setValue(tr("BrowseFolderNative"), m_batchSetting.getBrowseFolderNative());
    setting.setValue(tr("MdiShowMode"), m_batchSetting.getMdiShowMode());

    setting.endGroup();
    setting.beginGroup(tr("BatchCreationOption"));

    setting.setValue(tr("CreateScriptBefore"), m_batchSetting.getCreateScriptBefore());
    setting.setValue(tr("DefaultSaveFormat"), m_batchSetting.getDefaultSaveFormat());
    setting.setValue(tr("DefaultSavePatern"), m_batchSetting.getDefaultSavePatern());
    setting.setValue(tr("ScriptBeforePatern"), m_batchSetting.getScriptBeforePatern());
    setting.setValue(tr("SorterFileId"), m_batchSetting.getSorterFileId());
    setting.setValue(tr("SorterFileParam"), m_batchSetting.getSorterFileParam());

    setting.endGroup();
    setting.beginGroup(tr("PrintOption"));

    setting.setValue(tr("Orientation"), m_batchSetting.getOrientation());
    setting.setValue(tr("PaperSize"), m_batchSetting.getPaperSize());
    setting.setValue(tr("Resolution"), m_batchSetting.getResolution());
    setting.setValue(tr("Color"), m_batchSetting.getColor());
    setting.setValue(tr("MargingBottom"), m_batchSetting.getMargingBottom());
    setting.setValue(tr("MargingLeft"), m_batchSetting.getMargingLeft());
    setting.setValue(tr("MargingRight"), m_batchSetting.getMargingRight());
    setting.setValue(tr("MargingTop"), m_batchSetting.getMargingTop());

    setting.endGroup();
}

void MainWindow::on_actionCheckAll_triggered(){
//    MySortFilterProxyModel* model = qobject_cast<MySortFilterProxyModel*>(widget.treeView->model());
//    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(model->sourceModel());
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());
    sourceModel->allCheck();
}
void MainWindow::on_actionCheckSelected_triggered(){
//    MySortFilterProxyModel* model = qobject_cast<MySortFilterProxyModel*>(widget.treeView->model());
//    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(model->sourceModel());
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());

    if(sourceModel->getRoot() == NULL)
        return;
    
    QModelIndexList indexes = widget.treeView->selectionModel()->selectedRows();
    foreach(QModelIndex index, indexes){
//        index = model->mapToSource(index);
        FileLite* c = static_cast<FileLite*>(index.internalPointer());
        if(c->getCheckedState() != Qt::Checked){
            c->setCheckedState(Qt::Checked);
        }
    }
    widget.treeView->update();
}
void MainWindow::on_actionUnCheckAll_triggered(){
//    MySortFilterProxyModel* model = qobject_cast<MySortFilterProxyModel*>(widget.treeView->model());
//    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(model->sourceModel());
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());
    sourceModel->allUnCheck();
}
void MainWindow::on_actionUnCheckSelected_triggered(){
//    MySortFilterProxyModel* model = qobject_cast<MySortFilterProxyModel*>(widget.treeView->model());
//    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(model->sourceModel());
    QDirModelVeryLite* sourceModel = qobject_cast<QDirModelVeryLite*>(widget.treeView->model());

    if(sourceModel->getRoot() == NULL)
        return;
    
    QModelIndexList indexes = widget.treeView->selectionModel()->selectedRows();
    foreach(QModelIndex index, indexes){
//        index = model->mapToSource(index);
        FileLite* c = static_cast<FileLite*>(index.internalPointer());
        if(c->getCheckedState() != Qt::Unchecked){
            c->setCheckedState(Qt::Unchecked);
        }
    }
    widget.treeView->update();
}

void MainWindow::reloadFilterBatch(){
    widget.comboFilterBatch->blockSignals(true);
    widget.comboFilterBatch->setUpdatesEnabled(false);
    widget.comboFilterBatch->clear();
    
    QList<BatchMergeCriteria> criteriaList = DAOBatchMerge::self()->getAllBatchCriteria();
    BatchMergeCriteria currCriteria = DAOBatchMerge::self()->getCurrentBatchCriteria();
    int idx = -1;
    for (int i = 0; i < criteriaList.size(); i++) {
        BatchMergeCriteria criteria = criteriaList[i];
        if(currCriteria.id == criteria.id){
            idx = i;
        }
        widget.comboFilterBatch->addItem(criteria.name, criteria.id);
    }
    widget.comboFilterBatch->setCurrentIndex(idx);
    
    widget.comboFilterBatch->setUpdatesEnabled(true);
    widget.comboFilterBatch->blockSignals(false);
    
    on_comboFilterBatch_currentIndexChanged(idx);
}

